//
//  KoiTokenStore.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 19.03.25.
//

import Foundation
class KoiTokenStore {
    
    private static let userDefaults = UserDefaults.standard
    private static let login_user_token_pref = "login_user_token:"
    private static let access_token = login_user_token_pref + "a_t"
    private static let access_token_exp = login_user_token_pref + "a_t_exp"
    private static let refresh_token = login_user_token_pref + "r_t"
    
    
    static func saveToken(token: KoiToken?) {
        guard let token = token else { return }
        saveAccessToken(token: token.at)
        saveRefreshToken(token: token.rt)
        saveAccessTokenExp(exp: token.at_exp ?? 0)
    }
    
    static func getAccessToken() -> String {
        return userDefaults.string(forKey: access_token).orEmpty
    }
    
    static func getAccessTokenExp() -> Double {
        // test
        // return Date().timeIntervalSince1970 + 60*60*24 + 1
        return userDefaults.double(forKey: access_token_exp)
    }
    
    static func getRefreshToken() -> String {
        return userDefaults.string(forKey: refresh_token).orEmpty
    }
    
    static func saveAccessToken(token: String?) {
        userDefaults.set(token, forKey: access_token)
    }
    
    static func saveAccessTokenExp(exp: Double?){
        logger.debug("save token  \(exp ?? 0)")
        userDefaults.set(exp, forKey: access_token_exp)
    }
    
    static func saveRefreshToken(token: String?) {
        userDefaults.set(token, forKey: refresh_token)
    }
    
    static func removeToken() {
        userDefaults.removeObject(forKey: access_token)
        userDefaults.removeObject(forKey: refresh_token)
    }
}
